package com.zzyl.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;

import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourcesService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ResourcesServiceImpl implements ResourcesService {
    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    public List<ResourceVo> findResourceList(ResourceDto dto) {
        return resourceMapper.selectResourceList(dto);
    }

    @Override
    public TreeVo findResourceTree(TreeItemVo itemVo) {
        TreeItemVo rootItemVo = new TreeItemVo(SuperConstant.ROOT_PARENT_ID, "智慧养老院", new ArrayList<TreeItemVo>());
        ResourceDto dto = new ResourceDto();
        dto.setResourceType("m");
        List<ResourceVo> voList = resourceMapper.selectResourceList(dto);
        createTree(voList,rootItemVo);
        ArrayList<TreeItemVo> treeItemVos = new ArrayList<>();
        treeItemVos.add(rootItemVo);
        TreeVo vo = new TreeVo(treeItemVos);
        return vo;
    }

    @Override
    public void saveResource(Resource resource) {
        Resource parent = resourceMapper.selectByNo(resource.getParentResourceNo());
        if (!resource.getDataState().equals(parent.getDataState())){
            throw new BaseException(BasicEnum.PARENT_DEPT_DISABLE);
        }
        String no = "";
        List<Resource> list = resourceMapper.selectByParentNo(resource.getParentResourceNo());
        if (CollectionUtil.isEmpty(list)){
            no = NoProcessing.createNo(resource.getParentResourceNo(),false);
        }else {
            no = NoProcessing.createNo(list.get(0).getResourceNo(),true);
        }
        log.info(no);
        if (resource.getResourceType().equals("m") && !no.endsWith("000")){
            throw new BaseException(BasicEnum.BAD_MENU_NO);
        }
        resource.setResourceNo(no);
        resourceMapper.insert(resource);
    }

    private void createTree(List<ResourceVo> voList, TreeItemVo rootItemVo) {
        for (ResourceVo vo : voList) {
            if (vo.getParentResourceNo().equals(rootItemVo.getId())
                && vo.getResourceNo().endsWith("000")){
                TreeItemVo treeItemVo = new TreeItemVo(vo.getResourceNo(), vo.getResourceName(), new ArrayList<TreeItemVo>());
                rootItemVo.getChildren().add(treeItemVo);
                createTree(voList,treeItemVo);
            }
        }
    }
}
